//@ sourceURL=Roles_list.js
//加载安全角色列表相关配置
$(function () {
    //加载完Web资源和字段信息后执行
    $('body').on('queryview.loadedAttribute', function (e, attributeinfo) {
        console.log(attributeinfo)
        var statecol = $.grep(attributeinfo.attributeInfo, function (item, key) {
            return item.name == 'statecode';
        });
        if (statecol.length > 0) {
            statecol[0].render = function (ui) {
                var datas = ui.rowData;
                var dataIndx = ui.dataIndx;
                var column = ui.column;
                var name = datas['name'];
                var record = datas['statecode'];
                if (record == '1') {
                    return '<span class="label label-info">启用</span>';
                } else {
                    return '<span class="label label-default">禁用</span>';
                }
            }
        }
        attributeinfo.attributeInfo.push({
            "dataIndx": "displayname", "title": '授权', editable: false, "dataType": "string", "width": 100, align: 'center', "isprimaryfield": false, "attributetypename": "string", sortable: false,
            render: function (ui) {
                var datas = ui.rowData;
                var dataIndx = ui.dataIndx;
                var column = ui.column;
                var name = datas['name'];
                var roleid = datas['roleid'];
                if (name.toLowerCase() != 'administrator') {
                    var rowhtml = '<div class="btn-group btn-group-xs datatable-filter-wrap">' +
                        ' <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">' +
                        ' <span class="glyphicon glyphicon-lock"></span> 授权' +
                        ' <span class="caret"></span>' +
                        ' </button>' +
                        ' <ul class="dropdown-menu role-item-btn" data-roleid="'+roleid+'">'//加载完列表控件和数据时需要  role-item-btn

                    // var itemroleHtml = rolehtml;
                    // itemroleHtml = itemroleHtml.replace(/{{roleid}}/g, roleid);
                    return rowhtml  + ' </ul></div>';
                } else {
                    return '';
                }
            }
        })

    })

    //设置列表控件的参数
    $('body').on('queryview.setDataGridConfig', function (e, dconf) {
        var gridconfig = dconf.datagridconfig;
        //重新设置复选框字段的信息
        gridconfig.checkboxinfo = {
            title: "", dataIndx: "recordid", maxWidth: 30, minWidth: 30, align: "center", resizable: false,
            type: 'checkBoxSelection', cls: 'ui-state-default', sortable: false, editable: false,
            render: function (ui) {
                //console.log(primarykey);
                var datas = ui.rowData;
                var dataIndx = ui.dataIndx;
                var column = ui.column;
                var recordid = datas['roleid'];
                return '<input type="checkbox" value="' + recordid + '" name="recordid" class="">'
            },
            cb: { header: true, all: true },
        };
        gridconfig.rowDblClick= function (event, ui) {
            var id = $(ui.$tr).find('input[name="recordid"]').val();
            var url = ORG_SERVERURL + '/security/role/edit?id=' + id;
            entityIframe('show', url);

        }

    });

    //列表渲染完成后执行
    $('body').on('queryview.afterAjax', function (e, opts) {
        //{ grid: grid };  role-item-btn
        console.log('gridrefresh', $('.role-item-btn'))
        Xms.Ajax.Get('/api/security/resourceowners', {}, function (response) {
            console.log('queryview.refreshDataAndViewe', response)
            var res = Xms.Web.GetAjaxResult(response);
            var contents = res.content;
            var htmls = [];
            if (contents && typeof contents == 'object') {
                for (var i in contents) {
                    if (contents.hasOwnProperty(i)) {
                        var item = contents[i];
                        if(item.statecode == true){
                            if (item.uiendpoint && item.uiendpoint != '') {
                                htmls.push(' <li><a href="' + ORG_SERVERURL + item.uiendpoint + '?roleid={{roleid}}&resourcename=' + item.modulename + '"><span class="glyphicon glyphicon-lock"></span> ' + (item.modulelocalizedname || item.modulename) +'</a></li>')
                            } else {
                                htmls.push('<li><a href="' + ORG_SERVERURL + '/security/editrolepermission?roleid={{roleid}}&resourcename=' + item.modulename + '"><span class="glyphicon glyphicon-lock"></span> ' + (item.modulelocalizedname || item.modulename) +'</a></li>');
                            }
                        }
                    }
                }
            }
            $('.role-item-btn').each(function () {
                var roleid = $(this).attr('data-roleid');
                var lis = htmls.join('');
                lis = lis.replace(/{{roleid}}/g, roleid);
                $(this).html(lis)
            });

            opts.$context.find('.datatable-filter-wrap').xmsPosDropdown();
            console.log(res, response)
        }, false, false, false)
    })
})


function create_role(newWindow) {

    var   url = ORG_SERVERURL + '/security/role/create';

    if (newWindow) {
        //Xms.Web.OpenWindow(url);
        entityIframe('show', url);
    }
    else {
        location.href = url;
    }
}

function delete_role() {

    var event = event || window.event || arguments.callee.caller.arguments[0];
    var target = $('#datatable');
    Xms.Web.SelectingRow(event.target, false, true);
    var id = Xms.Web.GetTableSelected(target);
    Xms.Web.Del(id, '/api/security/role/deletebyid', false, function (response) {
        if (response.IsSuccess) {
            getFunction(target.attr('data-refresh'))();
            return;
        }
    });
}

function edit_role(newWindow) {
    var event = event || window.event || arguments.callee.caller.arguments[0];
    var target = $('#datatable');
    Xms.Web.SelectingRow(event.target, false, true);
    var id = Xms.Web.GetTableSelected(target);
    var url = '/security/role/edit?id=' + id;
    if (newWindow) {
        Xms.Web.OpenWindow(ORG_SERVERURL + url);
    }
    else {
        location.href = ORG_SERVERURL + url;
    }
}

function save_role(){
    var name = Xms.Page.getValue('name');
    if(name == ''){
        Xms.Web.Alert(true, '');
    }
    var description = Xms.Page.getValue('description');
    var data = {name: name, description: description};
    Xms.Web.Post('/api/security/role/create', data, false, function (response) {
        //Xms.Web.Toast(response.Content || response.ErrorMessage, response.IsSuccess);
        if(response.IsSuccess){
            Xms.Web.Event.publish('refresh');
            var toEditPage = function(){
                Xms.Web.Redirect('security/role/edit?id=' + response.Extra.id);
            };
            Xms.Web.Alert(true, response.Content || LOC_SAVED_SUCCESS, toEditPage, toEditPage);
        }
        else{
            Xms.Web.FailureHandler(response);
        }
    }, null, false, false, { jsonajax: true });
}

//状态更改
function update_rolestate(state) {
    var id = [];
    if (Xms.Page && Xms.Page.PageContext && Xms.Page.PageContext.RecordId) {
        id.push(Xms.Page.PageContext.RecordId);
    }
    else {
        var target = $('#datatable');
        id = Xms.Web.GetTableSelected(target);
    }
    if (!id || id.length == 0) {
        Xms.Web.Toast(LOC_NOTSPECIFIED_RECORD, false);
        return;
    }
    var data = {};
    data.entityid = Xms.Page.PageContext.EntityId;
    data.recordid = id;
    var action = '/api/security/role/setstate';
    $.extend(data, { "isenabled": state });
    Xms.Web.Post(action, data, false, function (response) {
        if (typeof refreshMethod !== "undefined") {
            eval(refreshMethod);
        }
        Xms.Web.Toast(response.Content || response.ErrorMessage, response.IsSuccess);
        $('.datagrid-view').cDatagrid('refreshDataAndView');
    }, null, false, false, { jsonajax: true });
}

function CopyRole(){
    var data = Xms.QueryView.getSelectedData();
    if(!data || data.length == 0){
        Xms.Web.Toast(LOC_NOTSPECIFIED_RECORD, false);
        return;
    }
    Xms.Web.Post('/api/security/role/copy', {roleid: data[0].roleid, name: data[0].name + '1'}, false, function(response){
        if (response.IsSuccess) {
            Xms.Web.Alert(true, response.Content);
            $('.datagrid-view').cDatagrid('refreshDataAndView');
            return;
        }
        Xms.Web.Alert(false, response.Content || response.ErrorMessage);
    }, null, true, false);
}